package at.jku.se.fastsell.app;

import java.util.List;

import at.jku.se.fastsell.app.R;
import at.jku.se.fastsell.data.Auction;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ItemAdapter extends ArrayAdapter<Auction> {

	Context context;
    int layoutResourceId;   
    List<Auction> itemList;
   
    public ItemAdapter(Context context, int layoutResourceId, List<Auction> itemList) {
        super(context, layoutResourceId, itemList);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.itemList = itemList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ItemHolder holder = null;
       
        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
           
            holder = new ItemHolder();
            
            holder.txtTitle = (TextView)row.findViewById(R.id.titleLine);
            holder.txtPrice = (TextView)row.findViewById(R.id.priceLine);
            holder.txtDate = (TextView)row.findViewById(R.id.dateLine);
           
            row.setTag(holder);
        }
        else
        {
            holder = (ItemHolder)row.getTag();
        }
       
        Auction item = itemList.get(position);
        holder.txtTitle.setText(item.getTitle());
        holder.txtPrice.setText("Euro: " + item.getCurPrice());
        
        long offset = 6*60*60*1000;
        long currTime = System.currentTimeMillis() + offset;
        if (currTime < item.getEnd()){
        	long diff = item.getEnd() - currTime;
			long diffSeconds = diff / 1000 % 60;          
			long diffMinutes = (diff / (60 * 1000)) % 60;          
			long diffHours = diff / (60 * 60 * 1000);    
			String erg = "";
			if (diffHours > 0){
				erg = diffHours + " h ";
			}
			erg = erg + diffMinutes + " min and " + diffSeconds + " seconds left";
			holder.txtDate.setText(erg);
        }else if (item.getBidCount() > 0){
        	holder.txtDate.setText("Auction finished: " + item.getHighestBidder());
        }else{
        	holder.txtDate.setText("Auction finished without bid");
        }
       
        return row;
    }
    
    @Override
    public void notifyDataSetChanged(){
    	
    }
   
    static class ItemHolder
    {
        ImageView imgIcon;
        TextView txtTitle;
        TextView txtPrice;
        TextView txtDate;
    }
}
